package be.redo.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import be.redo.model.entities.Employee;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/**
	 * @see be.redo.dao.EmployeeDAO#create(be.redo.model.entities.Employee)
	 */
	@Override
	public void create(Employee instance) {
		try {
			entityManager.persist(instance);
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	/**
	 * @see be.redo.dao.EmployeeDAO#read(long)
	 */
	@Override
	public Employee read(long id) {
		return entityManager.find(Employee.class, id);
	}

	/**
	 * @see be.redo.dao.EmployeeDAO#update(be.redo.model.entities.Employee)
	 */
	@Override
	public void update(Employee instance) {
		try {
			entityManager.merge(instance);
			entityManager.flush();
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	/**
	 * @see be.redo.dao.EmployeeDAO#delete(long)
	 */
	@Override
	public void delete(long id) {
		Employee instance = entityManager.find(Employee.class, id);
		if (instance != null) {
			entityManager.remove(instance);
			entityManager.flush();
		}
	}

	/**
	 * @see be.redo.dao.EmployeeDAO#findAll()
	 */
	@Override
	public List<Employee> findAll() {
		TypedQuery<Employee> query = entityManager.createNamedQuery(
				"findAllEmployees", Employee.class);
		return query.getResultList();
	}

	/**
	 * @see be.redo.dao.EmployeeDAO#count()
	 */
	@Override
	public int count() {
		TypedQuery<Number> query = entityManager.createNamedQuery(
				"findAantalEmployees", Number.class);
		return (query.getSingleResult()).intValue();
	}

	/**
	 * @see be.redo.finders.EmployeeFinders#findEmployeesByEmailLike(java.lang.String)
	 */
	@Override
	public List<Employee> findEmployeesByEmailLike(String email) {
		TypedQuery<Employee> query = entityManager.createNamedQuery(
				"findEmployeesByEmailLike", Employee.class);
		query.setParameter("email", email);
		return query.getResultList();
	}
}
